from rest_framework import serializers

from users.models import User


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'password')  # id默认有read_only=True
        extra_kwargs = {
            'username': {
                'max_length': 20,
                'min_length': 5,
                'required': True
            },
            'password': {
                'max_length': 20,
                'min_length': 8,
                'required': True
            }
        }

    def create(self, validate):
        """
        ModelSerializer在创建用户的时候没有实现密码加密，不符合需求，所以要重写
        """
        # 加密方法一
        user = super().create(validate)
        user.set_password(validate.get('password'))
        user.save()

        # # 方法二
        # user = User.objects.create_user(**validate)

        return user


class UserAddSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'password', 'email')
        read_only_fields = ('id', )
        extra_kwargs = {
            'username': {
                'max_length': 20,
                'min_length': 5
            },
            'password': {
                'max_length': 20,
                'min_length': 8,
                'write_only': True
            },
        }

        def create(self, validate):
            user = User.objects.create(**validate)

            return user


